package cn.wh.ymcc.mq.consumer;

import cn.wh.ymcc.dto.PayNotifyDto;
import cn.wh.ymcc.serivce.service.ICourseUserLearnService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQMessageListener(
        consumerGroup = "course-pay-notify-consumer",
        topic = "pay-notify-topic",
        selectorExpression = "pay-notify-tag",
        messageModel = MessageModel.BROADCASTING//  广播模式
)
@Slf4j
public class CourseNotifyConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseUserLearnService courseUserLearnService;

    @Override
    public void onMessage(MessageExt messageExt) {
        log.info("课程微服务：接收到支付成功的事务消息");
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0){
            return;//消息不对,直接签收
        }
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        PayNotifyDto payNotifyDto = JSONObject.parseObject(jsonStr, PayNotifyDto.class);
        if(StringUtils.isEmpty(payNotifyDto.getExtParams()) ){
            return;
        }
        courseUserLearnService.saveUserLear(payNotifyDto);

    }
}
